package com.ykzhujiang.lovespirit.parser;

import java.util.Calendar;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ykzhujiang.lovespirit.entity.Notice;
import com.ykzhujiang.lovespirit.util.Utility;

public class TJUParser extends Parser {
	public TJUParser() {

		resource_root = "http://bbs.tju.edu.cn";
		resource_pattern = "(?<=\\<a href=')(\\/TJUBBS\\/attach\\/[\\S]+?\\.\\w{1,4})(?=')";
		writer_pattern = "(?<=发信人: )(.+)(?=,)";
		title_pattern = "(?<=标  题: )(.+)(?=\\r\\n)";
		board_pattern = "(?<=信区: )(.+)(?=\\r\\n)";
		site_pattern = "(?<=发信站: )(.+)(?= \\()";
		content_pattern = "(?<=(本站\\(bbs\\.tju\\.edu\\.cn\\)\\r\\n))((?s).*?)(?=(※ 来源:．天大求实BBS)|\\z)";
		date_pattern = "(?<=\\()((\\w{3}) (\\w{3}) {1,2}(\\w{1,2}) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4}))(?=\\)(.{1,8})?,)";

		notice_pattern = "(?<=<table class\\=tb4>)((?s).*?)(?=<br><\\/table>)";
	}

	public int ParseResource(String text, Notice notice) {
		Pattern p = Pattern.compile(resource_pattern);
		Matcher m = p.matcher(text);
		while (m.find()) {
			String raw = resource_root + m.group(1);
			raw=raw.replaceAll("\\&amp;", "&");
			if (!notice.getResourceUrl().contains(raw)) {
				notice.getResourceUrl().add(raw);
			}
		}
		Vector urls = Utility.GetURLS(text);
		for (int i = 0; i < urls.size(); i++) {
			if (!notice.getResourceUrl().contains((String) urls.get(i))) {
				notice.getResourceUrl().add((String) urls.get(i));
			}
		}
		return 0;
	}
	public int ParseDate(String text, Notice notice) {
		Pattern p = Pattern.compile(date_pattern);
		Matcher m = p.matcher(text);
		int year, month, date, hour, min, sec;
		if (m.find()) {
			year = Integer.parseInt(m.group(8));
			month = Utility.GetMonth(m.group(3));
			date = Integer.parseInt(m.group(4));
			hour = Integer.parseInt(m.group(5));
			min = Integer.parseInt(m.group(6));
			sec = Integer.parseInt(m.group(7));
			Calendar c = notice.getCalDate();
			c.set(year, month, date, hour, min, sec);
			notice.setCalDate(c);
		}
		return 0;
	}

	public Notice ParseSingle(String url_text, String text) {
		Notice notice = new Notice();
		ParseResource(text, notice);
		text = Utility.RemoveHTMLTag(text);
		text = Utility.RemoveColorTag(text);
		ParseWriter(text, notice);
		ParseBoard(text, notice);
		ParseTitle(text, notice);
		ParseSite(text, notice);
		ParseDate(text, notice);
		ParseContent(text, notice);
		notice.setSourceUrl(url_text);
		return notice;
	}
}
